const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
const fs = require('fs');

function scanDir(dir, ret) {
    console.log('dir====>', dir);
    if (fs.existsSync(dir)) {
        const files = fs.readdirSync(dir);
        files.forEach(item => {
            const currentPath = `${dir}/${item}`;
            const stat = fs.statSync(currentPath);
            if (stat.isDirectory()) {
                scanDir(currentPath, ret);
            } else if (stat.isFile()) {
                if (item === 'page.json') {
                    let infoJson = {}, infoData = {};
                    try {
                        const pageExists = fs.existsSync(`${dir}/page.json`);
                        if (pageExists) {
                            infoJson = fs.readFileSync(`${dir}/page.json`);
                            infoData = JSON.parse(infoJson);
                        }
                    } catch (err) {
                        console.error('编译错误，错误信息:', err);
                    }
                    const fileName = dir.substr(dir.lastIndexOf('/') + 1);
                    console.log('file name ===>', fileName);
                    ret.push(new HtmlWebpackPlugin({
                        title: infoData.title ? infoData.title : 'XDesigner',
                        chunks: [`${dir.replace(path.resolve(__dirname, '../client/pages/'), '')}`],
                        inject: false,
                        template: path.resolve(__dirname, '../client/template.html'),
                        filename: `${dir.replace(path.resolve(__dirname, '../client/pages'), '')}.html`,
                        minify: {
                            collapseWhitespace: true,
                            preserveLineBreaks: true
                        }
                    }))
                }
            }
        })
    }
}

module.exports = (dir) => {
    let ret = []
    scanDir(dir, ret);
    return ret
}
